﻿using Learun.Util;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Learun.Application.TwoDevelopment.ZZDT_EC
{
    public class ec_notificationBLL
    {
        ec_notificationService ec_NotificationService;
        public ec_notificationBLL()
        {
            ec_NotificationService = new ec_notificationService();
        }

        public IEnumerable<ec_notificationEntity> GetUserAllNotification(string ProjectId, string User)
        {
            var ec_drawing_synBLL = new ec_drawing_synBLL();
            var ec_drawing_fileBll = new ec_drawing_fileBLL();
            var res = GetList("{RetrieveUserID:\"" + User + "\",checkFLG:\"0\",ProjectId:\"" + ProjectId + "\"}");
            foreach (var item in res)
            {
                var remarkObj = ec_drawing_synBLL.GetEntity(item.DrawingSynID, ProjectId);

                if (remarkObj != null)
                {
                    var DrawingObj = ec_drawing_fileBll.GetEntity(remarkObj.DrawingFileID, ProjectId);
                    if (DrawingObj != null)
                    {
                        item.Remark = remarkObj.Remark;
                        item.DrawingID = remarkObj.DrawingFileID;
                        item.DrawingName = DrawingObj.DrawingFileName;
                    }

                }

            }

            return res;
        }

        /// <summary>
        /// 保存实体数据（新增、修改）
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void SaveEntity(string keyValue, ec_notificationEntity entity, string ProjectId)
        {
            try
            {
                ec_NotificationService.SaveEntity(keyValue, entity, ProjectId);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

        /// <summary>
        /// checkFLG = 1
        /// <param name="keyValue">主键</param>
        /// <summary>
        /// <returns></returns>
        public void Approve(string keyValues, string ProjectId)
        {
            try
            {
                foreach (var keyValue in keyValues.Replace("，", ",").Split(','))
                {


                    var obj = ec_NotificationService.GetList("{ID:\"" + keyValue + "\",ProjectId:\"" + ProjectId + "\"}").FirstOrDefault();
                    if (obj != null)
                    {
                        obj.CheckFLG = 1;
                        obj.CheckTime = Time.Now.ToString();
                        ec_NotificationService.SaveEntity(keyValue, obj, ProjectId);
                    }
                }
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }
        /// <summary>
        /// 预检入时，自动比对，生成一些文本（比如新增了什么、修改了什么）
        /// <summary>
        /// <returns></returns>
        public string GenerateCompareRes(List<ec_enginedata_pixelEntity> entityList, string ProjectId, string DrawingID)
        {
            //新增的
            var Drawing = new ec_drawing_fileService().GetEntity(DrawingID, ProjectId);
            if (Drawing.IsCheckOut == 1 && Drawing.CheckOutUserID == LoginUserInfo.Get().userId) //确保本人操作
            {
                var res = "";
                //ADD
                ec_enginedataService ec_EnginedataService = new ec_enginedataService();
                string sql = $"t.CreateUserID='{LoginUserInfo.Get().userId}'";
                var tags = ec_EnginedataService.GetListBySQL(sql, ProjectId);
                var tagsNew = tags.Where(TAG => DateTime.Compare((DateTime)TAG.CreateTime, Time.Now) < 0 &&
                                                         DateTime.Compare((DateTime)TAG.CreateTime, (DateTime)Drawing.CheckOutTime) > 0);
                // 创建时间 早于 检入时间（当前）
                // 创建时间 晚于 检出时间
                res += "新增设备：";
                res += "\r\n";
                foreach (var TAG in tagsNew)
                {
                    res += $"【{TAG.ObjectTypeName}】，【{TAG.TagNumber}】。 ";
                }
                res += "------------------";
                res += "\r\n";
                res += "设备从本图的图面移除：";
                res += "\r\n";
                //DELETE
                var tagsExisted = ec_EnginedataService.GetListBySQL("", ProjectId).Where(TAG => DateTime.Compare((DateTime)TAG.CreateTime, (DateTime)Drawing.CheckOutTime) < 0).OrderBy(x => x.ObjectTypeName);
                //图纸上所有的pixel记录
                var pixelsExisted = new ec_enginedata_pixelService().GetList("{\"ProjectId\":\"" + ProjectId + "\",\"DrawingFileID\":\"" + DrawingID + "\"}").ToList();

                // 创建时间 早于 检出时间
                foreach (var TAG in tagsExisted)
                {
                    if (entityList == null || entityList.Count == 0)
                    {
                        break;
                        //提交的图纸上没有图元，但是数据库里有
                        //res += "提交的是空数据。";
                        //if (pixelsExisted.Exists(x => x.EngineDataID == TAG.EngineDataID))
                        //{
                        //    res += "提交空数据 ";
                        //    res += $"【{TAG.ObjectTypeName}】，【{TAG.TagNumber}】。 ";
                        //}
                        //else
                        //{
                        //    Console.WriteLine("本身图面上就没有");
                        //}
                    }
                    else // if (!entityList.Exists(x => x.EngineDataID == TAG.EngineDataID))
                    {
                        var pixelExistedTag = pixelsExisted.Where(x => x.EngineDataID == TAG.EngineDataID).ToList();


                        if (pixelExistedTag == null || pixelExistedTag.Count() == 0)
                        {
                            Console.WriteLine("本身图面上就没有");

                        }
                        else
                        {
                            bool foundFLG = false;
                            foreach (var piexlChecking in entityList)
                            {
                                if (pixelExistedTag.Exists(x => x.PixelCode == piexlChecking.PixelCode))
                                {
                                    foundFLG = true;
                                    entityList.Remove(piexlChecking);
                                    break; //至少有一个图元
                                }
                            }
                            if (!foundFLG)
                            {
                                //提交的图纸上没有图元，但是数据库里有
                                res += $"【{TAG.ObjectTypeName}】，【{TAG.TagNumber}】。 ";
                            }

                        }
                    }
                }
                return res;
            }
            else
            {
                return "";
            }

        }

        /// <summary>
        /// 获取列表数据
        /// <summary>
        /// <returns></returns>
        public IEnumerable<ec_notificationEntity> GetList(string queryJson)
        {
            try
            {
                return ec_NotificationService.GetList(queryJson);
            }
            catch (Exception ex)
            {
                if (ex is ExceptionEx)
                {
                    throw;
                }
                else
                {
                    throw ExceptionEx.ThrowBusinessException(ex);
                }
            }
        }

    }
}
